﻿using System;
using Microsoft.Devices.Sensors;

namespace IWantIn
{
    public static class ShakeDetection
    {
        static AccelerometerReadingEventArgs previousData;
        static int numShakes;

        // Two properties for controlling the algorithm
        public static int RequiredConsecutiveShakes { get; set; }
        public static double Threshold { get; set; }

        static ShakeDetection()
        {
            RequiredConsecutiveShakes = 1;
            Threshold = .7;
        }

        // Call this with the accelerometer data
        public static bool JustShook(AccelerometerReadingEventArgs e)
        {
            if (previousData != null)
            {
                if (IsShaking(previousData, e, Threshold))
                {
                    numShakes++;
                    if (numShakes == RequiredConsecutiveShakes)
                    {
                        // Just shook!
                        numShakes = 0;
                        return true;
                    }
                }
                else if (!IsShaking(previousData, e, .2))
                    numShakes = 0;
            }

            previousData = e;
            return false;
        }

        // It's a shake if the values in at least two dimensions
        // are different enough from the previous values
        static bool IsShaking(AccelerometerReadingEventArgs previous,
          AccelerometerReadingEventArgs current, double threshold)
        {
            double deltaX = Math.Abs(previous.X - current.X);
            double deltaY = Math.Abs(previous.Y - current.Y);
            double deltaZ = Math.Abs(previous.Z - current.Z);

            return (deltaX > threshold && deltaY > threshold) ||
                   (deltaY > threshold && deltaZ > threshold) ||
                   (deltaX > threshold && deltaZ > threshold);
        }
    }
}
